/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: LockControler
 * Author:   pc
 * Date:     2019/9/18 16:59
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.example.rabbitmqdemo.lock;

import com.example.rabbitmqdemo.service.AcountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.Semaphore;

/**
 * 〈功能：〉<br> 
 * 〈〉
 * @author liuhaoran
 * @create 2019/9/18 16:59
 * @since 1.0.0
 */
@Controller
@EnableAsync
public class LockControler {
	private int countSum=10;
	@Autowired
	AcountService acountService;
	Card card = new Card("银行卡");
	Paper paper1= new Paper("用户A");
	Paper paper2 = new Paper("用户B");
	Paper paper3 = new Paper("用户C");
	Thread cardone = new Thread(card);
	Thread thread1 = new Thread(paper1);
	Thread thread2 = new Thread(paper2);
	Thread thread3 = new Thread(paper3);
	@ResponseBody
	@PostMapping("sendlock")
	public String sendlock(){
		cardone.start();
		thread1.start();
		thread2.start();
		thread3.start();
		return "success";
	}
	@GetMapping("/userInfo/request")
	@ResponseBody
	public String Resquest(){
		Semaphore semaphore=new Semaphore(1);  //定义资源的总数量
		int availablePermits=semaphore.availablePermits();//可用资源数
		if(availablePermits>0){
			System.out.println("抢到资源");
		}else{
			System.out.println("资源已被占用，稍后再试");
			return "Resource is busy！";
		}
		try {
			semaphore.acquire(1);  //请求占用一个资源
			System.out.println("资源正在被使用");
			Thread.sleep(5000);//放大资源占用时间，便于观察
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			semaphore.release(1);//释放一个资源
			System.out.println("资源被释放");
		}
		return "Success";
	}
	@GetMapping("sendasync")
	@ResponseBody
	@Async
	public String sendAsync(){
		try {
			Thread.sleep(1000);
			acountService.asynctest1();
			acountService.asynctest2();
			acountService.asynctest3();
			acountService.asynctest4();
		}catch (InterruptedException e){
			e.printStackTrace();
		}
		return "success";
	}

}